<script setup lang="ts">
import type { UploadUserFile } from 'element-plus';

import type { IContextMenuItem } from '@vben-core/shadcn-ui';

import type {
  BreadCrumbCatalog,
  CatalogListData,
  RowType,
  ThumbListData,
} from './index';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { computed, onBeforeMount, reactive, ref, watch } from 'vue';

import { Page } from '@vben/common-ui';
import {
  ElBack,
  ElCheck,
  ElCircleClose,
  ElDelete,
  ElDocumentCopy,
  ElDownload,
  ElFiles,
  ElSearch,
  ElShare,
  ElView,
  IpSortOne,
} from '@vben/icons';

import { VbenContextMenu } from '@vben-core/shadcn-ui';
import { StorageManager } from '@vben-core/shared/cache';

import {
  ElBreadcrumb,
  ElBreadcrumbItem,
  ElButton,
  ElDivider,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElEmpty,
  ElIcon,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElPopover,
  ElTag,
} from 'element-plus';
import { Base64 } from 'js-base64';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { fileApi } from '#/api';
import { PREVIEW_IP } from '#/constant';
import { $t } from '#/locales';
import { useCatalogStore } from '#/store';

import {
  folderIcon,
  geojsonIcon,
  otherIcon,
  pdfIcon,
  shpIcon,
  tableIcon,
  tupianIcon,
  zipIcon,
} from './assets';
import {
  CreateFolderDialog,
  DetailDialog,
  FileViewer,
  PreviewDialog,
  PublishDialog,
  ShareFileDialog,
  Uploader,
} from './components';

type SortType = 'default' | 'name' | 'publishTime' | 'type';
type OrderType = 'asc' | 'desc';
// import KnowledgeRetrieve from './KnowledgeRetrieve.vue';
interface SortItemType {
  label: string;
  value: OrderType | SortType;
  active: boolean;
  divider?: boolean;
}
const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});
const catalogStore = useCatalogStore();
// 页面状态控制（布尔值）
const isDetail = ref(true);
const isLoading = ref(false);
const showUploader = ref(false);
const showShareFile = ref(false);
const showFileViewer = ref(false);
const showUnzipDialog = ref(false);
const showDetailDialog = ref(false);
const showPreviewDialog = ref(false);
const showPublishDialog = ref(false);
const isSelectedShapefile = ref(false);
const showCreateFolderDialog = ref(false);

// 用户 & 目录信息
const userId = storageManager.getItem('userId') as string;
const rootCatalog = storageManager.getItem('rootCatalog') as string;

// 搜索 & 过滤
const keyword = ref('');
const placeholderText = ref($t('page.resources.searchPlaceholder'));
const filterArray = [{ label: 'All (*.all)', value: 'All' }];

// 文件 & 预览相关
const dataTitle = ref('');
const previewName = ref('');
const previewSrc = ref('');
const emptyText = ref(' ');
const treeData = ref([]);

// 分页 & 排序
const sortMethod = ref('type');
const total = ref(1);
const pageSize = ref(10);
const currentPage = ref(1);
const highlightIndex = ref(-1);
let ids: any[] = [];
const selectedFiles = ref([] as any);
const currentSortMethod = ref<SortType>('default');
const currentSortOrder = ref<OrderType>('asc');
const currentSelectedCard = reactive({
  data: {} as CatalogListData,
});
const breadcrumbItemData = reactive({
  data: [] as BreadCrumbCatalog[],
});
const catalogList = reactive({
  data: [] as CatalogListData[],
});
const thumbCatalogList = reactive({
  data: [] as ThumbListData[],
});
const fileList = reactive({
  data: [] as UploadUserFile[],
});
const uploadFormData = reactive({
  data: {
    file: null,
    fileName: '',
    fileTemplate: '',
    srid: '',
    code: '',
    description: '',
  },
});
const imageSrc = (type: string) => {
  switch (type) {
    case 'csv':
    case 'xls':
    case 'xlsx': {
      return tableIcon;
    }
    case 'folder': {
      return folderIcon;
    }
    case 'geojson': {
      return geojsonIcon;
    }
    case 'gif':
    case 'jpg':
    case 'png': {
      return tupianIcon;
    }
    case 'pdf': {
      return pdfIcon;
    }
    case 'shp': {
      return shpIcon;
    }
    case 'zip': {
      return zipIcon;
    }
    default: {
      return otherIcon;
    }
  }
};
const sortOptions = ref<SortItemType[]>([
  {
    label: $t('page.resources.sortOptions.byDefault'),
    value: 'default',
    active: true,
  },
  {
    label: $t('page.resources.sortOptions.byFileName'),
    value: 'name',
    active: false,
  },
  {
    label: $t('page.resources.sortOptions.byDate'),
    value: 'publishTime',
    active: false,
  },
  {
    label: $t('page.resources.sortOptions.byFileType'),
    value: 'type',
    active: false,
  },
  {
    label: $t('page.resources.sortOptions.byAsc'),
    value: 'asc',
    active: true,
    divider: true,
  },
  {
    label: $t('page.resources.sortOptions.byDesc'),
    value: 'desc',
    active: false,
  },
]);
const realSortOptions = computed(() => {
  return sortOptions.value.map((option) => ({
    ...option,
    active:
      option.value === currentSortMethod.value ||
      option.value === currentSortOrder.value,
  }));
});
function updateEmptyText() {
  emptyText.value = $t('page.resources.emptyState1.text');
}
watch(showUploader, (newV) => {
  if (newV === false) {
    isSelectedShapefile.value = false;
    fileList.data = [];
    uploadFormData.data = {
      file: null,
      fileName: '',
      fileTemplate: '',
      srid: '4326',
      // eslint-disable-next-line unicorn/text-encoding-identifier-case
      code: 'UTF-8',
      description: '',
    };
    // console.log('对话框初始化！');
  }
});
watch(breadcrumbItemData, (newVal) => {
  catalogStore.setBreadCrumb(newVal.data);
  if (storageManager.getItem('breadcrumb')) {
    storageManager.removeItem('breadcrumb');
  }
  storageManager.setItem('breadcrumb', catalogStore.breadcrumb);
});

watch(
  () => $t('page.resources.myData.title'),
  (newTitle) => {
    dataTitle.value = newTitle;
    // console.log(dataTitle.value);
    breadcrumbItemData.data[0].title = dataTitle.value;
    placeholderText.value = $t('page.resources.search1.placeholder', {
      catalog: dataTitle.value,
    });
    updateEmptyText();
  },
);
const gridOptions: VxeGridProps<RowType> = {
  size: 'medium',
  height: '100%',
  checkboxConfig: {
    highlight: true,
    trigger: 'row',
    range: true,
  },
  rowConfig: {
    keyField: 'id',
    height: 55,
    isHover: true,
  },
  columns: [
    { type: 'checkbox', width: 80 },
    {
      field: 'name',
      title: '名称',
      width: '40%',
      align: 'left',
      sortable: true,
      slots: {
        default: 'icon-name',
      },
    },
    { field: 'type', title: '类型', sortable: true },
    { field: 'updatedTime', title: '创建时间', sortable: true },
    {
      field: 'size',
      title: '文件大小',
      sortable: true,
      slots: {
        default: 'size',
      },
    },
  ],
  exportConfig: {},
  // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
  keepSource: true,
  pagerConfig: {
    pageSize: 10,
    pageSizes: [10, 15, 20, 50],
  },

  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        selectedFiles.value.length = 0;
        return await fileApi.getChildren(
          catalogStore.currentCatalogId === '' &&
            catalogStore.rootCatalog === null
            ? rootCatalog
            : (breadcrumbItemData?.data[breadcrumbItemData?.data?.length - 1]
                ?.catalogId as string),
          page.pageSize,
          page.currentPage,
          keyword.value,
        );
      },
    },
  },
  toolbarConfig: {
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const selectedIds = computed(() => {
  return selectedFiles.value.map((item: { id: any }) => item.id);
});
const selectedCount = computed(() => {
  return selectedFiles.value.length;
});
const clearSlection = () => {
  selectedFiles.value = [];
  // eslint-disable-next-line no-use-before-define
  gridApi.grid.clearCheckboxRow();
};

const handleSelectionChange = () => {
  // eslint-disable-next-line no-use-before-define
  const selectRecords = gridApi.grid.getCheckboxRecords();
  // eslint-disable-next-line no-use-before-define
  const selectReserveRecords = gridApi.grid.getCheckboxReserveRecords();
  selectedFiles.value = [...selectRecords, ...selectReserveRecords];
  ids = selectRecords.map((item: any) => item.id);
};
const handleSortChange = (field: SortType, order: OrderType) => {
  if (!order) {
    currentSortMethod.value = 'default';
    currentSortOrder.value = 'asc';
    return;
  }
  currentSortMethod.value = field;
  currentSortOrder.value = order;
};
const gridEvents: VxeGridListeners<CatalogListData> = {
  checkboxChange: () => handleSelectionChange(),
  checkboxAll: () => handleSelectionChange(),
  sortChange: ({ field, order }) =>
    handleSortChange(field as SortType, order as OrderType),
};
const [Grid, gridApi] = useVbenVxeGrid({ gridEvents, gridOptions });
const isOptionDisabled = (sortMethod: OrderType | SortType) => {
  return sortMethod === 'desc' && currentSortMethod.value === 'default';
};
const handleSortData = (sortMethod: SortType, order: 'asc' | 'desc') => {
  if (sortMethod === 'default') {
    currentSortOrder.value = 'asc';
    gridApi.grid.clearSort();
    return;
  }
  gridApi.grid.setSort(
    {
      field: sortMethod,
      order,
    },
    true,
  );
};
const handleUpdateSort = (sortMethod: OrderType | SortType) => {
  if (
    sortMethod === currentSortMethod.value ||
    sortMethod === currentSortOrder.value
  ) {
    return;
  }
  if (sortMethod === 'asc' || sortMethod === 'desc') {
    currentSortOrder.value = sortMethod;
  } else {
    currentSortMethod.value = sortMethod;
  }
  handleSortData(currentSortMethod.value, currentSortOrder.value);
};
const searchedthumbFiles = computed(() => {
  // 确保 keyword 和 thumbCatalogList.data 都是响应式的
  const keywordLower = keyword.value?.toLowerCase() || '';
  const filteredData = thumbCatalogList.data.filter((data) => {
    return !keywordLower || data.name.toLowerCase().includes(keywordLower);
  });
  return filteredData;
});
const sortedFileT = computed(() => {
  const sortedT = [...searchedthumbFiles.value];
  switch (sortMethod.value) {
    case 'date': {
      sortedT.sort(
        (a, b) =>
          new Date(a.updatedTime).getTime() - new Date(b.updatedTime).getTime(),
      );
      break;
    }
    case 'name': {
      sortedT.sort((a, b) => a.name.localeCompare(b.name));
      break;
    }
    case 'type': {
      sortedT.sort((a, b) => a.type.localeCompare(b.type));
      break;
    }
    default: {
      break;
    }
  }
  return sortedT;
}) as any;
const realSelectedFileData = computed(() => {
  return {
    id: currentSelectedCard.data.id,
    label: currentSelectedCard.data.name,
    type: currentSelectedCard.data.type,
    catalogId: storageManager.getItem('currentCatalogId'),
  } as any;
});

// 刷新数据
const flushCatalogList = async () => {
  isLoading.value = true;
  emptyText.value = ' ';
  const catalogId =
    catalogStore.currentCatalogId === '' && catalogStore.rootCatalog === null
      ? rootCatalog
      : (breadcrumbItemData?.data[breadcrumbItemData?.data?.length - 1]
          ?.catalogId as string);
  try {
    const response = await fileApi.getChildren(
      catalogId,
      pageSize.value,
      currentPage.value,
      keyword.value,
    );
    catalogList.data = [...response.body];
    gridApi.query();
    total.value = response.count;
  } catch (error) {
    console.error('Error fetching catalog:', error);
  } finally {
    isLoading.value = false; // 无论请求成功或失败，都会执行
  }
};
// 获取整个文件列表
const getChildrenofcatalog = () => {
  const catalogId =
    catalogStore.currentCatalogId === '' && catalogStore.rootCatalog === null
      ? rootCatalog
      : (breadcrumbItemData?.data[breadcrumbItemData?.data?.length - 1]
          ?.catalogId as string);

  fileApi
    .getChildrenofcatalog(catalogId)
    .then((res) => {
      thumbCatalogList.data = [] as ThumbListData[];
      // 检查 res.data 是否有效，并确保是数组
      const data = res;
      if (Array.isArray(data)) {
        data.forEach((file: any) => {
          thumbCatalogList.data.push(file);
        });
      } else {
        console.warn('Received data is not an array or is empty:', data);
      }
    })
    .catch((error) => {
      console.error('Error when fetching catalog list:', error);
    });
};
const popBreadCrumbItem = (id: number) => {
  breadcrumbItemData.data = breadcrumbItemData.data.filter(
    (item) => item.id <= id,
  );
  getChildrenofcatalog();
  keyword.value = '';
};
const clickBreadCrumbItem = (catalog: BreadCrumbCatalog) => {
  popBreadCrumbItem(catalog.id);
  flushCatalogList();
};
const jumpCatalog = (catalog: BreadCrumbCatalog) => {
  catalogStore.updateCurrentCatalogId(catalog.catalogId);
  storageManager.removeItem('currentCatalogId');
  storageManager.setItem('currentCatalogId', catalogStore.currentCatalogId);

  placeholderText.value = $t('page.resources.search1.placeholder', {
    catalog: catalog.title,
  });
  keyword.value = '';
  clickBreadCrumbItem(catalog);
};
const backCatalog = () => {
  const index = breadcrumbItemData.data.length - 1;
  const breadcrumb = breadcrumbItemData.data[index - 1] as BreadCrumbCatalog;
  if (index - 1 < 0) {
    ElMessage({
      type: 'warning',
      message: $t('page.resources.cannotNavigateUpMessage'),
    });
    keyword.value = '';
    flushCatalogList();
    return;
  }
  catalogStore.updateCurrentCatalogId(breadcrumb.catalogId);
  storageManager.removeItem('currentCatalogId');
  storageManager.setItem('currentCatalogId', catalogStore.currentCatalogId);
  jumpCatalog(breadcrumb);
};
// 进入文件夹
const enterFolder = async (folder: CatalogListData) => {
  catalogStore.updateCurrentCatalogId(folder.id);
  storageManager.removeItem('currentCatalogId');
  storageManager.setItem('currentCatalogId', catalogStore.currentCatalogId);
  catalogList.data = [] as CatalogListData[];
  highlightIndex.value = -1;
  breadcrumbItemData.data.push({
    id: breadcrumbItemData.data.length,
    title: folder.name,
    catalogId: folder.id,
  });
  placeholderText.value = $t('page.resources.search1.placeholder', {
    catalog: folder.name,
  });
  keyword.value = '';
  flushCatalogList();
  getChildrenofcatalog();
};

// 预览
const previewData = (data: CatalogListData) => {
  const id = data.id;
  previewName.value = data.name;
  if (
    previewName.value &&
    typeof previewName.value === 'string' &&
    (previewName.value.toLowerCase().endsWith('.shp') ||
      previewName.value.toLowerCase().endsWith('.geojson'))
  ) {
    ElMessage({
      type: 'warning',
      message: $t('page.resources.publishOnlyPreviewMessage'),
    });
    return;
  }
  fileApi
    .getFilePreviewUrl(id)
    .then((data) => {
      const previewURL = data;
      // @ts-ignore
      const previewURLString = previewURL.toString();
      const base64String = Base64.encode(previewURLString);
      previewSrc.value = `${PREVIEW_IP}/onlinePreview?url=${encodeURIComponent(base64String)}`;
      showPreviewDialog.value = true;
    })
    .catch((error) => {
      console.error(error);
    });
};
// 解压
const unZip = async (file: any) => {
  const catalogId = file.id || rootCatalog;
  const data = {
    userId,
    fileId: currentSelectedCard.data.id,
    catalogId,
  };
  showUnzipDialog.value = true;

  await fileApi.unZip(data);

  showUnzipDialog.value = false;
  ElMessage({
    type: 'success',
    message: '文件解压成功！',
  });
  flushCatalogList();
  getChildrenofcatalog();
};
const getFolderTree = async () => {
  showFileViewer.value = true;
  try {
    const response = await fileApi.getFolderTree(rootCatalog);
    treeData.value = response;
  } catch (error) {
    console.error('Error:', error);
    showUnzipDialog.value = false;
  }
};
// 下载
const downloadFile = (data: CatalogListData) => {
  const fileId = data.id;
  const fileName = data.name;
  fileApi
    .downloadFile(fileId)
    .then((response) => {
      const blob = new Blob([response]);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      a.click();
      URL.revokeObjectURL(url);
    })
    .catch((error) => {
      console.error('文件下载失败:', error);
    });
};
// / 通用删除函数
const deleteCatalogById = async (
  catalogId: string,
  successMessage: string,
  _failureMessage: string,
) => {
  // console.log('----catalogId is', catalogId);
  await fileApi.deleteCatalog(catalogId);

  flushCatalogList();
  getChildrenofcatalog();
  ElMessage({
    type: 'success',
    message: successMessage,
  });
};

// 删除单个文件夹
const deleteCatalog = async (catalogId: string) => {
  await ElMessageBox.confirm(
    $t('page.resources.deleteFolderConfirmMessage'),
    $t('page.resources.deleteFolderConfirmTitle'),
    {
      confirmButtonText: $t('page.resources.confirmButtonText'),
      cancelButtonText: $t('page.resources.cancelButtonText'),
      type: 'warning',
    },
  );

  await deleteCatalogById(
    catalogId,
    $t('page.resources.deleteFolderSuccessMessage'),
    $t('page.resources.deleteFolderFailureMessage'),
  );
};

// 删除文件 file
const performDeleteFile = async (fileId: string) => {
  const catalogId =
    catalogStore.currentCatalogId === '' && catalogStore.rootCatalog === null
      ? rootCatalog
      : breadcrumbItemData.data[breadcrumbItemData.data.length - 1].catalogId;

  const deleteFileDTO = {
    catalogId,
    fileId: typeof fileId === 'string' ? fileId : currentSelectedCard.data.id,
    userId,
  };

  try {
    // 1. 删除文件
    await fileApi.deleteFile(deleteFileDTO);

    // 2. 如果文件删除成功，删除相关的标签
    // const tagResponse = await fileTagApi.deleteFileTag(fileId);
    // if (tagResponse.code === '200') {
    //   // console.log(`文件 ${fileId} 的标签已成功删除`);
    // } else {
    //   console.warn(`文件 ${fileId} 的标签删除失败`);
    // }
    // 3. 刷新目录列表
    flushCatalogList();
    getChildrenofcatalog();

    // 5. 更新知识库
    // const { datasetId, documentId } = await getKnowledgeInfo();
    // if (!(datasetId && documentId)) {
    //   // console.log(datasetId, documentId);
    //   ElMessage.warning('知识库不存在，无法同步到知识库');
    //   return true;
    // }
    // const {
    //   data: { data: segments },
    // } = await segmentApi.querySegments(datasetId, documentId, fileId);
    // if (segments.length > 0) {
    //   await segmentApi.deleteSegment(datasetId, documentId, segments[0].id);
    // }
  } catch (error) {
    console.error('请求出错:', error);
    return false;
  }
};

const deleteFile = async (fileId: string) => {
  await performDeleteFile(fileId);
  ElMessage.success($t('page.resources.deleteFileSuccessMessage'));
};

// 批量删除
const pileDelete = async () => {
  const folderIds: string[] = [];
  const fileIds: string[] = [];

  ids.forEach((item) => {
    if (item.includes('-')) {
      folderIds.push(item);
    } else {
      fileIds.push(item);
    }
  });
  selectedFiles.value = [];

  if (ids.length > 0) {
    let successCount = 0;

    // 显示警告消息
    ElMessageBox.confirm(
      $t('page.resources.batchDeleteWarningMessage'),
      $t('page.resources.deleteFolderConfirmTitle'),
      {
        confirmButtonText: $t('page.resources.confirmButtonText'),
        cancelButtonText: $t('page.resources.cancelButtonText'),
        type: 'warning',
      },
    )
      .then(async () => {
        if (folderIds.length > 0) {
          for (const folderId of folderIds) {
            await deleteCatalog(folderId);
            successCount++;
          }
        }

        if (fileIds.length > 0) {
          for (const fileId of fileIds) {
            await performDeleteFile(fileId);
            successCount++;
          }
        }

        // 显示成功消息
        ElMessage({
          type: 'success',
          message: $t('page.resources.batchDeleteSuccessMessage', {
            successCount,
          }),
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: $t('page.resources.cancelDeleteMessage'),
        });
      });
  } else {
    ElMessage({
      type: 'warning',
      message: $t('page.resources.nothingSelectedWarningMessage'),
    });
  }
};

// 获取详细信息
const fetchDetail = async (fileId: string) => {
  const response = await fileApi.getFileInfo(fileId);
  currentSelectedCard.data = response;
  if (currentSelectedCard.data !== null) {
    showDetailDialog.value = true;
  }
};
// 定义右键菜单的选项
const getContextMenus = (data: any): IContextMenuItem[] =>
  [
    {
      text: '预览',
      icon: ElView,
      handler: () => {
        previewData(data);
      },
      key: 'preview',
      show: data.type !== 'folder',
    },
    {
      text: '解压',
      icon: ElFiles,
      handler: () => {
        getFolderTree();
        currentSelectedCard.data = data;
      },
      key: 'unzip',
      show: data.type === 'zip',
    },
    {
      text: '下载',
      icon: ElDownload,
      handler: () => {
        downloadFile(data);
      },
      key: 'download',
      show: data.type !== 'folder',
    },
    {
      text: '分享',
      icon: ElShare,
      handler: () => {
        showShareFile.value = true;
        currentSelectedCard.data = data;
      },
      key: 'share',
      show: data.type !== 'folder',
    },
    {
      text: '删除',
      icon: ElDelete,
      handler: () =>
        data.type === 'folder' ? deleteCatalog(data.id) : deleteFile(data.id),
      key: 'delete',
      show: true,
    },
    {
      text: '详情',
      icon: ElDocumentCopy,
      handler: () => {
        fetchDetail(data.id);
      },
      key: 'detail',
      show: data.type !== 'folder',
    },
  ].filter((item) => item.show);
// 发布
const openPublishDialog = (row: any) => {
  showPublishDialog.value = true;
  currentSelectedCard.data = row;
};
watch(
  () => $t('page.resources.myData.title'),
  (newTitle) => {
    dataTitle.value = newTitle;
    breadcrumbItemData.data[0].title = dataTitle.value;
    placeholderText.value = $t('page.resources.search1.placeholder', {
      catalog: dataTitle.value,
    });
  },
);
onBeforeMount(async () => {
  try {
    breadcrumbItemData.data = [];
    breadcrumbItemData.data.push({
      id: 0,
      title: $t('page.resources.myData.title'),
      catalogId: rootCatalog,
    });
    storageManager.setItem('currentCatalogId', rootCatalog);
    flushCatalogList();
    getChildrenofcatalog();
  } catch (error) {
    console.error('Error when fetching catalog list:', error);
  }
});
const isGeoFile = (fileName: string) => {
  return (
    fileName.toLowerCase().endsWith('.shp') ||
    fileName.toLowerCase().endsWith('.geojson') ||
    /\.(?:jpg|png|gif|tif|tiff)$/i.test(fileName)
  );
};
</script>
<template>
  <Page
    oncontextmenu="return false"
    onselectstart="return false"
    title=""
    auto-content-height
    class="flex h-full flex-col"
  >
    <template #title>
      <div class="flex items-center whitespace-nowrap">
        <ElIcon size="30px" class="cursor-pointer" @click="backCatalog">
          <ElBack />
        </ElIcon>
        <ElDivider direction="vertical" border-style="hidden" />
        <ElBreadcrumb separator="/">
          <ElBreadcrumbItem
            v-for="catalog in breadcrumbItemData.data"
            :key="catalog.id"
          >
            <a @click="jumpCatalog(catalog)">
              {{ catalog.title }}
            </a>
          </ElBreadcrumbItem>
        </ElBreadcrumb>
      </div>
    </template>

    <template #extra>
      <div class="space-x-2">
        <ElButton @click="showCreateFolderDialog = true">新建文件夹</ElButton>
        <ElButton @click="showUploader = true">上传</ElButton>
        <ElButton @click="isDetail = !isDetail">切换查看方式</ElButton>
      </div>
    </template>

    <template v-if="!isDetail">
      <!-- **卡片视图** -->
      <div
        v-if="sortedFileT.length > 0"
        class="grid h-full w-full grid-cols-2 gap-4 overflow-auto rounded bg-white p-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 dark:bg-black"
        style="
          grid-template-rows: repeat(auto-fill, minmax(170px, 1fr));
          grid-auto-rows: 1fr;
        "
      >
        <div
          v-for="file in sortedFileT"
          :key="file.id"
          class="cursor-pointer"
          :title="file.name"
          @dblclick="file.type === 'folder' ? enterFolder(file) : null"
        >
          <VbenContextMenu
            :menus="getContextMenus"
            :handler-data="file"
            :modal="false"
          >
            <div class="rounded-lg border p-3 shadow-sm hover:shadow-md">
              <img
                :src="imageSrc(file.type)"
                class="mx-auto h-28 w-32 object-contain"
              />
              <div class="mt-2 truncate text-center text-sm font-medium">
                {{ file.name }}
              </div>
            </div>
          </VbenContextMenu>
        </div>
      </div>
      <div
        v-else
        class="flex h-full w-full items-center justify-center bg-white"
      >
        <ElEmpty description="暂无文件，去上传" />
      </div>
    </template>

    <template v-else>
      <!-- **表格视图** -->
      <Grid>
        <template #toolbar-tools>
          <div class="multi-delete flex items-center">
            <div class="flex items-center" v-if="selectedIds.length > 0">
              <div class="flex items-center">
                <ElIcon>
                  <ElFiles />
                </ElIcon>
                &nbsp;
                <span>
                  {{ $t('page.resources.selectedTitle', { selectedCount }) }}：
                </span>
              </div>
              <div
                class="w-[200px] overflow-hidden text-ellipsis whitespace-nowrap"
              >
                <ElPopover
                  :key="file.id"
                  :disabled="selectedFiles.length < 3"
                  placement="top-start"
                  width="250"
                  trigger="hover"
                  v-for="file in selectedFiles"
                >
                  <template #reference>
                    <ElTag style="cursor: pointer" size="large">
                      {{
                        file.name.length > 10
                          ? `${file.name.slice(0, 10)}...`
                          : file.name
                      }}
                    </ElTag>
                  </template>
                  <ElTag
                    v-for="item in selectedFiles"
                    :key="item.id"
                    style="cursor: pointer"
                    size="default"
                  >
                    {{ item.name }}
                  </ElTag>
                </ElPopover>
              </div>
            </div>
            <ElDivider direction="vertical" border-style="hidden" />
            <ElButton
              v-if="selectedFiles.length > 0"
              size="default"
              plain
              :icon="ElCircleClose"
              @click="clearSlection"
            >
              取消
            </ElButton>
            <ElButton
              v-if="selectedFiles.length > 0"
              class="mr-4"
              size="default"
              plain
              title="批量删除文件"
              type="danger"
              :icon="ElDelete"
              @click="pileDelete()"
            >
              删除
            </ElButton>
          </div>
          <div class="toolbar flex items-center">
            <ElInput
              v-model="keyword"
              size="default"
              :placeholder="placeholderText"
              clearable
              @clear="() => gridApi.reload()"
              @keyup.enter="() => gridApi.reload()"
            >
              <template #append>
                <ElButton @click="() => gridApi.reload()" default>
                  <ElIcon> <ElSearch /> </ElIcon>
                </ElButton>
              </template>
            </ElInput>
            <ElDropdown placement="bottom-end" class="ml-3 flex items-center">
              <ElButton :icon="IpSortOne" circle />
              <template #dropdown>
                <ElDropdownMenu>
                  <ElDropdownItem
                    v-for="option in realSortOptions"
                    :key="option.value"
                    :divided="option.divider"
                    :disabled="isOptionDisabled(option.value)"
                    @click="() => handleUpdateSort(option.value)"
                  >
                    <span class="w-20">{{ option.label }}</span>
                    <ElIcon v-if="option.active">
                      <ElCheck />
                    </ElIcon>
                  </ElDropdownItem>
                </ElDropdownMenu>
              </template>
            </ElDropdown>
          </div>
        </template>
        <template #icon-name="{ row }">
          <VbenContextMenu
            :menus="getContextMenus"
            :handler-data="row"
            :modal="false"
          >
            <div
              @dblclick="row.type === 'folder' ? enterFolder(row) : null"
              class="flex cursor-pointer items-center"
            >
              <img :src="imageSrc(row.type)" class="mr-2 h-6 w-6" />
              <span class="truncate">{{ row.name }}</span>
              <ElDivider direction="vertical" border-style="hidden" />
              <ElButton
                v-if="isGeoFile(row.name)"
                @click="
                  (e) => {
                    e.stopPropagation();
                    openPublishDialog(row);
                  }
                "
              >
                发布
              </ElButton>
            </div>
          </VbenContextMenu>
        </template>
        <template #size="{ row }">
          <span class="truncate">
            {{
              row.size > 0
                ? row.size < 1048576
                  ? `${Math.ceil(row.size / 1024)}KB`
                  : `${(row.size / 1024 / 1024).toFixed(2)}MB`
                : '-'
            }}
          </span>
        </template>
      </Grid>
    </template>
    <!-- 新建文件夹对话框 -->
    <CreateFolderDialog
      v-model="showCreateFolderDialog"
      :user-id="userId"
      :root-catalog="rootCatalog"
      @refresh="() => (isDetail ? flushCatalogList() : getChildrenofcatalog())"
    >
      <template #footer>
        <div class="flex justify-end space-x-2">
          <ElButton type="primary"> 创建 </ElButton>
          <ElButton @click="showCreateFolderDialog = false">
            {{ $t('page.resources.cancel') }}
          </ElButton>
        </div>
      </template>
    </CreateFolderDialog>
    <!-- 预览对话框 -->
    <PreviewDialog
      v-if="showPreviewDialog"
      :preview-src="previewSrc"
      :is-preview-dialog-show="showPreviewDialog"
      :data-name="previewName"
      @close-preview-dialog="showPreviewDialog = false"
    />
    <!-- 解压对话框 -->
    <FileViewer
      v-model="showUnzipDialog"
      v-if="showFileViewer"
      :is-file-viewer-show="showFileViewer"
      :data-name="$t('page.resources.unzip')"
      :filter-array="filterArray"
      :catalog-id="rootCatalog"
      @close-file-viewer="showUnzipDialog = false"
      @confirm-select="unZip"
    />
    <!-- 分享对话框 -->
    <ShareFileDialog
      v-model:visible="showShareFile"
      v-if="showShareFile"
      :current-selected-card="currentSelectedCard"
      @share-success="showShareFile = false"
    />
    <!-- 上传对话框 -->
    <Uploader
      v-model="showUploader"
      v-if="showUploader"
      upload-type="personal"
      @upload-success="isDetail ? flushCatalogList() : getChildrenofcatalog()"
    />
    <!-- 发布对话框 -->
    <PublishDialog
      :is-publish-dialog-show="showPublishDialog"
      :current-selected-data="realSelectedFileData"
      :is-public="false"
      @close-publish-dialog="showPublishDialog = false"
      v-if="showPublishDialog"
    />
    <!-- 详细信息对话框 -->
    <DetailDialog
      v-model:visible="showDetailDialog"
      v-if="showDetailDialog"
      :file-data="currentSelectedCard.data"
    />
  </Page>
</template>
